myApp.controller('plan_ProjectListController', function ($scope, $rootScope, $uibModal, $stateParams, $http, ngDialog, $filter) {
    $scope.info = {};
    $scope.id = $stateParams.id;
    $scope.info.projectList = [];
    $scope.info.project = {};
    $scope.info.index = 0;
    $scope.info.userlock = true;
    $scope.info.PMlock = true;
    $scope.info.ApplyInfo = [];
    $scope.info.userList = [];
    $scope.info.p_name = {};
    $scope.info.ProjectEditionList = [];
    $scope.info.userlists = [];

    $scope.total = $scope.info.projectList.length;
    $scope.page = {size: 20, index: 1};

    $scope.info.checked = false;
    //项目内存在状态不为TO_INTEGRATION的工程时，项目不能转测集成
    $scope.info.can_Integration = false;

    $scope.info.modifiAble = true;

    $scope.info.integrationInfo = null;

    if (!isUserCanOperateByRole('plan_admin', 'pm')) {
        $scope.info.modifiAble = false;
    }

    $scope.ProjectList = function () {

        LoadModal($uibModal);
        $http.get(beetle_plan_url + '/project_plan/getPlanProjectList?withIntPro=true&token_id=' + getTokenId() + '&plan_id=' + $scope.id).success(function (data) {
            closeModal();
            $scope.info.projectList = data.data;
            angular.forEach($scope.info.projectList, function (projects) {
                projects.projectInfo = projects.project_name.split("_")[1];
                var branchTip = '<table class="table table-bordered">';
                branchTip += '<tr><td>当前分支:</td><td>' + projects.project_name + '</td></tr>';
                if (projects.svn_from != null) {
                    branchTip += '<tr><td>来源:</td><td>' + projects.svn_from + '</td></tr>';
                }
                if (projects.from_version != null) {
                    branchTip += '<tr><td>来源版本号:</td><td>' + projects.from_version + '</td></tr>';
                }
                if (projects.from_svn_version != null) {
                    branchTip += '<tr><td>来源svn号:</td><td>' + projects.from_svn_version + '</td></tr>';
                }
                branchTip += '</table>';

                projects.branchTip = branchTip;
                $scope.getProjectEditionList(projects)
            })
        }).error(function (data) {
            alert(data.message);
            closeModal()
        })

    };

    $scope.keepAgent = function () {

        var apply = false;
        for (var i = 0; i < $scope.info.ApplyInfo.length; i++) {
            if ($scope.info.ApplyInfo[i].agent_ip != undefined && $scope.info.ApplyInfo[i].agent_ip != null && $scope.info.ApplyInfo[i].agent_ip != '') {
                apply = true
            }
        }

        if (!apply) {
            alert('该项目尚未申请虚拟机或者还未分配！');
            return
        }

        openDialog(ngDialog, $scope, "确定要申请保留七天么?", true, function (val) {
            if (!val) {
                return;
            }
            $http.get(ucloud_master_url + '/api/v1/apply_record/keep?plan_id=' + $scope.id + '&token_id=' + getTokenId()).success(function (data) {
                if (data.success == true) {
                    alert('保留成功！');
                } else {
                    alert(data.msg);
                }
            })
        })
    };


    //跳转工程构建页
    $scope.link = function (i) {
        setStorage('project_go_back', '1');
        window.location.href = "#/menu/project/" + i.project_name;
    };

    $scope.getProjectEditionList = function (object) {
        LoadModal($uibModal);
        $http.get(beetle_plan_url + '/project/getProjectEditionList?token_id=' + getTokenId() + '&project_name=' + object.project_name).success(function (data) {
            closeModal();
            object.ProjectEditionList = data.data;
            angular.forEach(object.ProjectEditionList, function (edition) {
                if (edition.editionNum == 'default') {
                    object.build_status = edition.showNum.split('(')[1].split(')')[0];
                }
            });
        }).error(function (data) {
            alert(data.message);
            closeModal()
        })
    };
    $scope.updateProjectEdition = function (object) {
        LoadModal($uibModal);
        $http.get(beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + object.project_name + '&type=to_test&edition_num=' + object.to_test_edition + '&plan_id=' + $scope.id).success(function (data) {
            closeModal();
            if (data.success == false) {
                alert(data.msg)
            }
        }).error(function (data) {
            alert(data.message);
            closeModal()
        })

    };
    $scope.getUser = function () {
        LoadModal($uibModal);
        $http.get(python_url + '/api/v1/user/?token_id=' + getTokenId()).success(function (data) {
            $scope.info.userList = data.data;
            closeModal();
        }).error(function (data) {
            alert(data.message);
            closeModal();
        })
    };


    $scope.ProjectFindbyId = function () {
        $scope.info.integrationInfo = null;
        doBeetleGet($http, $uibModal, beetle_plan_url + '/project_plan/getPlanList?isEmergency=1&token_id=' + getTokenId() + '&plan_id=' + $scope.id + '&isShowOnline=true', function (data) {
            $scope.info.project = data.data[0];
            $scope.info.project.member = "";
            $scope.info.userlists = [];
            $scope.info.project.expect_integration_date = new Date($scope.info.project.expect_integration_date);
            $scope.info.project.start_date = new Date($scope.info.project.start_date);
            $scope.info.project.end_date = new Date($scope.info.project.end_date);
            $scope.info.project.expect_release_date = new Date($scope.info.project.expect_release_date);

            angular.forEach($scope.info.project.members, function (data) {
                angular.forEach($scope.info.userList, function (user) {
                    if (data.account == user.account) {
                        $scope.info.project.member += data.realname + " ";
                        $scope.info.userlists.push(user);
                        return
                    }
                })
            });
            doBeetleGet($http, $uibModal, beetle_plan_url + '/integration/getIntegrationByPlan?token_id=' + getTokenId() + '&plan_id=' + $scope.id, function (data) {
                if (data.success) {
                    $scope.info.integrationInfo = data.data[0];
                }
            });
        });
    };

    $scope.title = function (index) {
        if (index == 0) {
            $scope.getUser();
            $scope.ProjectList();
            $scope.ProjectFindbyId();

        }
        // $scope.ProjectFindbyId();
        $scope.info.index = index;
        if (index == 1) {
        }

        if (index == 2) {
            $scope.ProjectFindbyId();
        }

        if (index == 3) {
            $scope.apply_record();
        }
        if (index == 4) {
            var count = 0;
            angular.forEach($scope.info.projectList, function (pro) {
                if (pro.package_type != 'maven_jar' && pro.project_status != 'TO_INTEGRATION') {
                    count = 1;
                    return
                }
            });
            if (count == 0) {
                $scope.info.can_Integration = true;
            }
        }
    };
    $scope.title(0);


    $scope.del = function (i) {
        //判断工程是否为集成计划的主干分支，如果是主干分支，不允许在页面操作删除
        if (i.plan_id != $scope.info.project.plan_id) {
            openDialogAlert(ngDialog, $scope, '集成计划主干分支不能删除,如果确定要删除,请联系系统管理员王健!');
            return;
        }

        openDialog(ngDialog, $scope, "删除不可恢复，请确认！", true, function (val) {
            if (!val) {
                return;
            }
            openDialog(ngDialog, $scope, "是否要删除工程的svn目录?", true, function (val) {
                doBeetleGet($http, $uibModal, beetle_plan_url + '/project_plan/delPlanProject?token_id=' + getTokenId() + '&trunk_name=' + i.trunk_name + '&plan_id=' + $scope.id + '&is_del_svn=' + val, function (data) {
                    if (data.success) {
                        $scope.ProjectList();
                    } else {
                        openDialogAlert(ngDialog, $scope, data.msg);
                    }
                })
            });
        })
    };

    $scope.changePlanPro = function (i) {
        $rootScope.changePlanProjectTemplate($scope.id, i.trunk_name, function () {
            $scope.ProjectList();
        }, function () {
            $scope.ProjectList();
        })
    };

    $scope.Refresh = function () {
        openDialog(ngDialog, $scope, "会重置项目的描述和人员信息，确认吗？", true, function (val) {
            if (!val) {
                return;
            }
            LoadModal($uibModal);
            $http.get(beetle_plan_url + '/zentao/initProjectPlanInfoByProjectId?token_id=' + getTokenId() + '&zentao_id=' + $scope.info.project.zt_id).success(function (data) {
                closeModal();
                if (data.success == true) {
                    $scope.ProjectFindbyId();

                } else {
                    alert(data.msg)
                }
            }).error(function (data) {
                alert(data.message);
                closeModal()
            })
        })
    };

    $scope.initPlanMembers = function () {
        openDialog(ngDialog, $scope, "会重置项目的人员信息，确认吗？", true, function (val) {
            if (!val) {
                return;
            }
            LoadModal($uibModal);
            $http.get(beetle_plan_url + '/zentao/initProjectPlanMembersByProjectId?token_id=' + getTokenId() + '&zentao_id=' + $scope.info.project.zt_id).success(function (data) {
                closeModal();
                if (data.success == true) {
                } else {
                    alert(data.msg);
                }
            }).error(function (data, header, config, status) {
                alert(data.message);
                closeModal()
            }).error(function (data) {
                alert(data.message);
                closeModal()
            })
        })
    };

    $scope.addUsers = function () {
        if ($scope.info.userlock == true) {
            $scope.info.userlock = false;
        } else {
            LoadModal($uibModal);
            $scope.info.project.member = "";
            $scope.info.members = [];
            angular.forEach($scope.info.userlists, function (data) {
                $scope.info.project.member += data.realname + " ";
                $scope.info.members.push(data);


            });

            $http.post(beetle_plan_url + '/project_plan/addPlanMembers', {

                token_id: getTokenId(),
                list: JSON.stringify($scope.info.members),
                plan_id: $scope.id
            }).success(function (data) {
                closeModal();
                if (data.success == true) {
                    $scope.info.userlock = true;
                } else {
                    alert(data.msg);
                }
            }).error(function (data) {
                alert(data.message);
                closeModal();
            })
        }

    };

    $scope.CloseUsers = function () {
        if ($scope.info.userlock == false) {
            $scope.info.userlock = true;
        }
    };

    $scope.editPM = function () {
        var PM_name = "";
        var account = "";
        if ($scope.info.PMlock == true) {
            $scope.info.oldPM = $scope.info.project.PM_name;
            $scope.info.PMlock = false;
        } else {
            if (angular.isString($scope.info.project.PM_name)) {
                $scope.info.PMlock = true;
                return false;
            } else {
                PM_name = $scope.info.project.PM_name.realname;
                account = $scope.info.project.PM_name.account;
                $scope.info.project.PM_name = PM_name;
                LoadModal($uibModal);
                $http.get(beetle_plan_url + '/project_plan/updatePlanPM?token_id=' + getTokenId() + '&account=' + account + '&plan_id=' + $scope.id + '&realname=' + PM_name).success(function (data) {
                    closeModal();
                    if (data.success == true) {
                        $scope.info.project.PM_name = PM_name;
                        $scope.info.PMlock = true;
                    } else {
                        alert(data.msg)
                    }
                }).error(function (data) {
                    alert(data.message);
                    closeModal();
                })

            }
            // })
            $scope.ProjectFindbyId();
        }
    };
    $scope.ClosePM = function () {
        if ($scope.info.PMlock == false) {
            $scope.info.project.PM_name = $scope.info.oldPM;
            $scope.info.PMlock = true;
        }
    };

    $scope.apply_record = function () {
        LoadModal($uibModal);
        $http.get(beetle_plan_url + '/project_plan/getUcloudApplyInfo?token_id=' + getTokenId() + '&plan_id=' + $scope.id).success(function (data) {
            closeModal();
            $scope.info.ApplyInfo = data.data;
        }).error(function (data) {
            alert(data.message);
            closeModal();
        })
    };

    $scope.toAgent = function (apply) {
        window.location.href = "#/menu/newucList/" + apply.agent_ip;
    };


    $scope.project_edit = function (object) {
        $rootScope.editionToTestTemplate(object.project_name, "TEST", function () {
            $scope.ProjectList();
        });
    };

    $scope.updateToIntegrationEdition = function (object) {
        $rootScope.editionToTestTemplate(object.project_name, "INTEGRATION", function () {
            $scope.ProjectList();
        });
    };

    $scope.updatePlanInfo = function () {

        // return false
        if ($scope.info.project.start_date > $scope.info.project.end_date) {
            alert('开始时间大于结束时间请重新选择');
            return false;
        }
        LoadModal($uibModal);
        $http.get(beetle_plan_url + '/project_plan/updatePlanInfo?token_id=' + getTokenId() + '&plan_id=' + $scope.id + '&start_date=' + $filter('date')($scope.info.project.start_date, "yyyy-MM-dd") + '&end_date=' + $filter('date')($scope.info.project.end_date, "yyyy-MM-dd") + '&integration_date=' + $filter('date')($scope.info.project.expect_integration_date, "yyyy-MM-dd") + '&release_date=' + $filter('date')($scope.info.project.expect_release_date, "yyyy-MM-dd")).success(function (data) {
            closeModal();
            if (data.success == false) {
                alert(data.msg)
            }
        }).error(function (data) {
            alert(data.message);
            closeModal()
        })
    };
    $scope.add = function () {
        $rootScope.addPlanProjectTemplate($scope.id, function () {
            $scope.ProjectList();
        }, function () {
            $scope.ProjectList();
        })
    };

    $scope.doIntegration = function () {
        // var flag = true;
        // var name = '';
        // angular.forEach($scope.info.projectList, function (pro) {
        //     if(pro.project_status != 'PRO_MERGED' && ((pro.isOnBeetle == '0' && pro.package_type != 'maven_jar') || (pro.package_type == 'ad'))){
        //         if (pro.to_integration_edition == null || pro.to_integration_edition == '') {
        //             flag = false;
        //             name = name + pro.trunk_name + ',';
        //         }
        //     }
        // });
        // if (!flag) {
        //     openDialogAlert(ngDialog, $scope, "工程" + name.substring(0, name.length - 1) + "申请集成版本不能为空!");
        //     return
        // }
        LoadModal($uibModal);
        $http.get(beetle_plan_url + '/project_plan/toIntegrationPlan?plan_id=' + $scope.id + '&token_id=' + getTokenId()).success(function (data) {
            closeModal();
            if (data.success == true) {
                window.location.href = '#/menu/planList/';
            } else {
                alert(data.msg)
            }
        }).error(function (data) {
            alert(data.message);
            closeModal()
        });
    };

    $scope.updateTestStatusConfirm = function (info, flag) {
        if (!info.integrationing_edition) {
            openDialogAlert(ngDialog, $scope, "当前集成测试版本为空，不能测试通过!");
            return
        }

        var msg = flag ? "测试通过" : "测试不通过";
        openDialog(ngDialog, $scope, "确定要将版本" + info.integrationing_edition + "标记为" + msg + "么?", true, function (f) {
            if (!f) {
                return;
            }
            $scope.updateTestStatus(info, flag)
        });
    };

    //测试通过/不通过
    $scope.updateTestStatus = function (info, flag) {
        var type = 'cancel_hand_over';
        if (flag) {
            type = 'hand_over';
        }
        ;

        doBeetleGet($http, $uibModal, beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + info.project_name + '&type=' + type + '&edition_num=' + info.integrationing_edition + '&plan_id=' + $scope.info.project.plan_id, function (data) {
            if (!data.success) {
                openDialogAlert(ngDialog, $scope, data.msg);
            }
        });
    };
});